package abc.certificate;

import cn.com.cqcca.util.encoders.Base64;
import com.ceba.cebacer.EnterpriseType;
import com.ceba.cebautils.CerParseUtils;

import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;

public class CertificationFactory {
	private static final int FILE = 0;
	private static final int TOKEN = 1;
	public static int certificationType = TOKEN;
	public static PrivateKeyAndCertificationChain getPrivateKeyAndCertificationChain(String alias) throws Exception{
		PrivateKeyAndCertificationChain privateKeyAndCertificationChain= null;
		if(certificationType == FILE){
			privateKeyAndCertificationChain = KeyStoreUtils.getPrivateKeyAndCertificationChain(alias);
		}else if(certificationType == TOKEN){
			privateKeyAndCertificationChain = WindowsCertificates.getPrivateKeyAndCertificationChain(alias);
			if(privateKeyAndCertificationChain !=null && privateKeyAndCertificationChain.certificationChain !=null
					&& privateKeyAndCertificationChain.certificationChain.length >1){
				Certificate[] roots = getAllCerList(privateKeyAndCertificationChain.privateKey.getEncoded()) ;
				if( roots!=null && roots.length >1){
					privateKeyAndCertificationChain.certificationChain[1] = roots[1];
				}
			}
		}
		return privateKeyAndCertificationChain;
		
	}
	

	/**
	 * 获取所有证书链
	 * @param signCert
	 * @return
	 * @throws CertificateException 
	 */
	public static Certificate[] getAllCerList(byte[]signCert) throws CertificateException{
		List<byte[]> rootList = new ArrayList<byte[]>();
		rootList.add(0,Base64.decode(EnterpriseType.
				getCer(EnterpriseType.TYPE_SHACA_ROOT_G2_RSA.getCode(), true)));
		rootList.add(1,Base64.decode(EnterpriseType.
				getCer(EnterpriseType.TYPE_SHACA_ROOT_G2_RSA.getCode(), false)));
		return  CerParseUtils.constructRSACertChain(signCert,rootList);
	}
	
}